﻿using WCS.Tools;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using WCS.API.Tools;
using WCS.Entities;
using WCS.ViewModels;
using WCS.Entities.Api;
using Warehouse.Services.Repository;
using WCS.Entities.User;

namespace WCS.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [AllowAnonymous]
    public class AuthController : ControllerBase
    {
        private readonly IMemoryCache cache;
        private readonly Repository<UserInfo> userInfoRepository;
        private IConfiguration configuration;
        public AuthController(
            IMemoryCache cache,
            Repository<UserInfo> userInfoRepository,
            IConfiguration configuration)
        {
            this.cache = cache;
            this.userInfoRepository = userInfoRepository;
            this.configuration = configuration;
        }


        /// <summary>
        /// 生成图片验证码
        /// </summary>
        /// <param name="codeType">验证码类型 0：纯数字 1：数字+字母 2：数字运算 默认1</param>
        /// <returns></returns>
        [HttpGet()]
        public async Task<ApiResult> Captcha(string? codeType = "1")
        {
            string uuid = Guid.NewGuid().ToString().Replace("-", "");
            var codeInfo = new VerifyCode();
            await Task.Run(() =>
            {
                if (codeType == "1")
                {
                    codeInfo = CreateCodeHelper.CreateVerifyCode(4, VerifyCodeType.CHAR);
                }
                else if (codeType == "2")
                {
                    codeInfo = CreateCodeHelper.CreateVerifyCode(4, VerifyCodeType.ARITH);
                }
                else if (codeType == "0")
                {
                    codeInfo = CreateCodeHelper.CreateVerifyCode(4, VerifyCodeType.NUM);
                }


            });
            var obj = new { key = uuid, image = codeInfo.Base64Str };

            await cache.GetOrCreateAsync(uuid, x =>
            {
                x.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);
                return Task.FromResult(codeInfo.Code);
            });
            return ApiResultHelp.Success(obj);
        }


        [HttpPost]
        public async Task<ApiResult> Login([FromBody] UserInfoDto userInfoDto)
        {

            //#region 【1】验证验证码是否正确
            //if (cache.Get(userInfoDto.Key)==null)
            //{
            //    return ApiResultHelper.Error(410,"验证码已经过期!");
            //}
            //var originCode = cache.Get(userInfoDto.Key) as string;
            //if (originCode.ToLower() !=userInfoDto.Code.ToLower())
            //{
            //    return ApiResultHelper.Error(411, "验证码错误!");
            //}

            //cache.Remove(userInfoDto.Key);
            //#endregion

            #region 【2】验证用户名和密码是否正确
            if (!userInfoRepository.IsExist(u => u.UserName == userInfoDto.UserName))
            {
                return ApiResultHelp.Error(412, "用户名不存在!");
            }
            var user = await userInfoRepository.FindAsync(x => x.UserName == userInfoDto.UserName);
            if (user.Password != MD5Utils.Md5(userInfoDto.Password))
            {
                return ApiResultHelp.Error(413, "密码不正确!");
            }
            #endregion

            #region【3】生成JwtToken
            //权限集合 eg *:*:*,system:user:list
            string token = JwtHelper.CreateToken(configuration, user);
            return ApiResultHelp.Success(token);

            #endregion
        }


        [HttpPost]
        [Authorize]
        public ApiResult Logout([FromServices] IHttpContextAccessor accessor)
        {
            var claim = accessor?.HttpContext?.SignOutAsync(JwtBearerDefaults.AuthenticationScheme);
            return ApiResultHelp.Success();
        }



    }
}
